package vn.ugame.filter;

import java.io.IOException;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.model.bl.ModuleManager;
import vn.ugame.model.entity.Module;

public class RequestFilter implements Filter {
    
    private FilterConfig filterConfig;
    
    public RequestFilter() {
    }
    
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String requestURI = httpRequest.getRequestURI();
        requestURI = requestURI.replaceAll(httpRequest.getContextPath(), "");
        
        if ("/".equals(requestURI)) {
            requestURI = "/store";
        }
        
        if (requestURI.startsWith("/ugame")) {
            chain.doFilter(request, response);
            return;
        }
        
        ModuleManager manager = new ModuleManager(null);
        List<Module> modules = manager.getAllModules();
        for (Module module : modules) {
            if (requestURI.toLowerCase().startsWith("/" + module.getName().toLowerCase())) {
                RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/ugame/" + requestURI);
                dispatcher.forward(request, response);
                return;
            }            
        }
        
        chain.doFilter(request, response);
    }
    
    public void destroy() {
    }
}
